package moonteam.moonisland.utils;

import net.milkbowl.vault.economy.Economy;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.plugin.RegisteredServiceProvider;
import static org.bukkit.Bukkit.getServer;

public class EcoUtils {

    private final static boolean HAS_VALUE = setupEconomy();
    private static Economy economy = null;

    private EcoUtils() {}

    private static boolean setupEconomy() {
        if (getServer().getPluginManager().getPlugin("Vault") == null) {
            return false;
        }
        RegisteredServiceProvider<Economy> rsp = Bukkit.getServer().getServicesManager().getRegistration(Economy.class);
        if (rsp == null) {
            LogUtils.send("Failed to load");
            return false;
        }
        economy = rsp.getProvider();
        return true;
    }

    public static void add(Player player, double money) {
        if(!HAS_VALUE) {
            return;
        }
        try {
            economy.bankDeposit(player.getName(), money);
        } catch (Exception error) {
            LogUtils.send("");
        }
    }

    public static void remove(Player player, double money) {
        if(!HAS_VALUE) {
            return;
        }
        try {
            if(!economy.has(player, money)) {
                return;
            }
            economy.withdrawPlayer(player, money);
        } catch (Exception error) {
            LogUtils.send("");
        }
    }

    public static void reset(Player player) {
        if(!HAS_VALUE) {
            return;
        }
        economy.withdrawPlayer(player, economy.getBalance(player));
    }

    public static String info(Player player) {
        if(!HAS_VALUE) {
            return null;
        }
        return String.valueOf(economy.getBalance(player));
    }

}
